package com.zhuziym.ketfile;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import java.util.List;

import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.core.logging.LogLevel;
import org.pentaho.di.core.util.EnvUtil;
import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobEntryResult;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;

/**
 * 从文件执行kettle
 * 
 * @author MI
 *
 */
public class KettleFile {

	/**
	 * java 调用 kettle 的job
	 * 
	 * @param path
	 * 
	 * @param jobname
	 * 
	 * @return
	 */
	public static String runJob(String[] params, String jobPath, String path) {
		try {
			KettleEnvironment.init(true);
			// jobname 是Job脚本的路径及名称
			JobMeta jobMeta = new JobMeta(jobPath, null);
			/*
			 * jobMeta.setVariable("KETTLE_HOME", path); jobMeta.setVariable("sqlstr",
			 * "SELECT t.id id , t.name 名字, t.rela 关系 FROM family t;");
			 * jobMeta.setVariable("sqlPath", path);
			 */

			Job job = new Job(null, jobMeta);
			job.setLogLevel(LogLevel.ROWLEVEL);
			job.start();
			job.waitUntilFinished();

			job.setFinished(true);
			if (job.isFinished()) {
				List<JobEntryResult> jobEntryResults = job.getJobEntryResults();
				for (JobEntryResult jobEntryResult : jobEntryResults) {
					System.out.println("执行步骤=" + jobEntryResult.getJobEntryName() + ",执行状态="
							+ jobEntryResult.getResult().getResult());
				}

			}
			// 执行 打印的日志 等全在这个xml中
			String basicXml = job.getResult().getBasicXml();
			System.out.println("----------------------------------------------------");
			// System.out.println(job.getResult().getLogText());
			boolean result = job.getResult().getResult();
			System.out.println("KettleFile.runJob()" + result);
			if (job.getErrors() > 0) {
				System.out.println("transformation error");
			} else {
				System.out.println("transformation successfully");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 运行转换文件方法
	 * 
	 * @param params  多个参数变量值
	 * @param ktrPath 转换文件的路径，后缀ktr
	 */
	public static void runTransfer(String[] params, String ktrPath, String kettleHome) {
		Trans trans = null;
		try {
			// 转换元对象
			KettleEnvironment.init(true);// 初始化
			EnvUtil.environmentInit();
			TransMeta transMeta = new TransMeta(ktrPath);

			// 加变量
			/*
			 * transMeta.setVariable("sqlstr",
			 * "SELECT t.id id , t.name 名字, t.rela 关系 FROM family t;");
			 * transMeta.setVariable("sqlPath",
			 * "C:/Users/admin/Desktop/kettle_3/2017-07-03/out");
			 */
			// 转换

			trans = new Trans(transMeta);
			// 执行转换 日志放在这里合适，
			trans.setLogLevel(LogLevel.ROWLEVEL);
			trans.execute(params);
			// 等待转换执行结束
			trans.waitUntilFinished();
			// 执行结果
			boolean result = trans.getResult().getResult();
			// 抛出异常
			if (trans.getErrors() > 0) {
				throw new Exception("There are errors during transformation exception!(传输过程中发生异常)");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws URISyntaxException, IOException {
		// TODO 配置JNDI文件位置
		URL jndiFile = KettleFile.class.getClassLoader().getResource("conf/simple-jndi");
		String path = Paths.get(jndiFile.toURI()).toFile().getCanonicalPath();
		String paths = jndiFile.toString();

		System.setProperty("java.naming.factory.initial", "org.osjava.sj.SimpleContextFactory");
		// TODO 如果此处是paths则 有问题，原因未知 (会提示 java.io.File parameter must be a directory.
		System.setProperty("org.osjava.sj.root", path);
		System.setProperty("org.osjava.sj.delimiter", "/");

		// TODO 配置JNDI文件位置 /end
//		String base_pathString = "C:/soft/data-integration/ketFile";
//		runTransfer(null, base_pathString + "/1test.ktr", null);
		// runJob(null, base_pathString + "/1test.kjb", null);

	}
}
